<script setup>
import { onMounted, watch, nextTick, onBeforeUnmount, ref } from "vue";
import * as echarts from "echarts";
import "echarts-gl";
import { useScaleStore } from "@/stores/scaleStore";

const props = defineProps({
  title: String,
  gridData: Object,
  roadPath: Array,
  closeEvent: Function,
});

const closeClick = () => {
  props?.closeEvent();
};

let chartInstance = null;
const chartDom = ref(null);
const boxWrapRef = ref(null);
const headerRef = ref(null);
const isDragging = ref(false);
const startPos = ref({ x: 0, y: 0 });
const currentPos = ref({ x: 0, y: 0 });
const currentScale = ref(1); // 当前窗口缩放比例
const isResizing = ref(false);
const resizeDirection = ref(null);
const startSize = ref({ width: 450, height: 400 });
const currentSize = ref({ width: 450, height: 400 });

const scaleStore = useScaleStore();

// 监听scaleStore的变化
watch(
  () => scaleStore.currentScale,
  (newScale) => {
    currentScale.value = newScale || 1;
  },
  { immediate: true }
);

const handleMouseDown = (e) => {
  // 检查是否是缩放区域
  if (e.target.classList.contains("resize-handle")) {
    isResizing.value = true;
    resizeDirection.value = e.target.dataset.direction;
    startSize.value = { ...currentSize.value };
    startPos.value = { x: e.clientX, y: e.clientY };

    e.stopPropagation();
    e.preventDefault();
    document.addEventListener("mousemove", handleResizeMove);
    document.addEventListener("mouseup", handleResizeEnd);
    return;
  }

  // 原有拖动逻辑
  if (!headerRef.value || !headerRef.value.contains(e.target)) return;

  const adjustedX = e.clientX / currentScale.value;
  const adjustedY = e.clientY / currentScale.value;

  isDragging.value = true;
  startPos.value = {
    x: adjustedX - currentPos.value.x,
    y: adjustedY - currentPos.value.y,
  };

  e.stopPropagation();
  e.preventDefault();

  document.addEventListener("mousemove", handleMouseMove);
  document.addEventListener("mouseup", handleMouseUp);
};

const handleMouseMove = (e) => {
  if (!isDragging.value) return;

  const adjustedX = e.clientX / currentScale.value;
  const adjustedY = e.clientY / currentScale.value;

  const newX = adjustedX - startPos.value.x;
  const newY = adjustedY - startPos.value.y;

  currentPos.value = { x: newX, y: newY };

  if (boxWrapRef.value) {
    boxWrapRef.value.style.left = `${newX}px`;
    boxWrapRef.value.style.top = `${newY}px`;
  }

  e.preventDefault();
};

const handleMouseUp = () => {
  isDragging.value = false;
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
};

const handleResizeMove = (e) => {
  if (!isResizing.value) return;

  const deltaX = (e.clientX - startPos.value.x) / currentScale.value;
  const deltaY = (e.clientY - startPos.value.y) / currentScale.value;

  const newSize = { ...currentSize.value };

  switch (resizeDirection.value) {
    case "e":
      newSize.width = Math.max(400, startSize.value.width + deltaX);
      break;
    case "s":
      newSize.height = Math.max(300, startSize.value.height + deltaY);
      break;
    case "se":
      newSize.width = Math.max(400, startSize.value.width + deltaX);
      newSize.height = Math.max(300, startSize.value.height + deltaY);
      break;
  }

  currentSize.value = newSize;
  updateChartSize();
  e.preventDefault();
};

const handleResizeEnd = () => {
  isResizing.value = false;
  resizeDirection.value = null;
  document.removeEventListener("mousemove", handleResizeMove);
  document.removeEventListener("mouseup", handleResizeEnd);
};

const updateChartSize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

const processGridData = () => {
  if (!props.gridData?.value.data?.length || !props.gridData.value.header)
    return [];

  const { lo1, lo2, la1, la2, dx, dy, nx, ny } = Object.fromEntries(
    Object.entries(props.gridData.value.header).map(([key, value]) => [
      key,
      isNaN(value) ? value : Number(value),
    ])
  );
  const heightData = props.gridData.value.data.map(Number);

  let roadLonMin = Infinity,
    roadLonMax = -Infinity;
  let roadLatMin = Infinity,
    roadLatMax = -Infinity;

  if (props.roadPath?.value?.length) {
    props.roadPath.value.forEach((point) => {
      roadLonMin = Math.min(roadLonMin, point.lon);
      roadLonMax = Math.max(roadLonMax, point.lon);
      roadLatMin = Math.min(roadLatMin, point.lat);
      roadLatMax = Math.max(roadLatMax, point.lat);
    });

    const lonPadding = (roadLonMax - roadLonMin) * 2;
    const latPadding = (roadLatMax - roadLatMin) * 2;
    roadLonMin -= lonPadding;
    roadLonMax += lonPadding;
    roadLatMin -= latPadding;
    roadLatMax += latPadding;
  } else {
    roadLonMin = lo1;
    roadLonMax = lo2;
    roadLatMin = la1;
    roadLatMax = la2;
  }

  const result = [];
  for (let j = 0; j < ny; j++) {
    const lat = la1 + j * dy;
    if (lat < roadLatMin || lat > roadLatMax) continue;

    for (let i = 0; i < nx; i++) {
      const lon = lo1 + i * dx;
      if (lon < roadLonMin || lon > roadLonMax) continue;

      const index = j * nx + i;
      if (index < heightData.length) {
        result.push([
          lon,
          lat,
          isNaN(heightData[index]) ? 0 : heightData[index],
        ]);
      }
    }
  }

  return result;
};

const processRoadData = () => {
  if (!props.roadPath?.value.length) return [];

  const surfaceData = processGridData();
  if (surfaceData.length === 0) return [];

  return [
    {
      coords: props.roadPath.value.map((point) => {
        let closest = surfaceData[0];
        let minDist = Infinity;

        surfaceData.forEach((d) => {
          const dist = Math.sqrt(
            Math.pow(d[0] - point.lon, 2) + Math.pow(d[1] - point.lat, 2)
          );
          if (dist < minDist) {
            minDist = dist;
            closest = d;
          }
        });

        return [point.lon, point.lat, closest[2]];
      }),
      lineStyle: {
        width: 4,
      },
    },
  ];
};

const initChart = async () => {
  await nextTick();
  if (!chartDom.value) return;

  chartInstance = echarts.init(chartDom.value);
  window.addEventListener("resize", () => {
    chartInstance?.resize();
  });
  updateChart();
};

const updateChart = () => {
  if (!chartInstance) return;

  const surfaceData = processGridData();
  const roadData = processRoadData();

  if (surfaceData.length === 0) {
    chartInstance.setOption({
      title: {
        text: "暂无SSH数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#fff",
          fontSize: 16,
        },
      },
    });
    return;
  }

  const calcRange = (arr, index, fallbackMin, fallbackMax) => {
    if (!arr || arr.length === 0) return { min: fallbackMin, max: fallbackMax };

    let min = Infinity;
    let max = -Infinity;

    for (const item of arr) {
      min = Math.min(min, item[index]);
      max = Math.max(max, item[index]);
    }

    return {
      min: isFinite(min) ? min - 0.6 : fallbackMin,
      max: isFinite(max) ? max + 0.6 : fallbackMax,
    };
  };

  const lonRange = calcRange(surfaceData, 0, 110, 126);
  const latRange = calcRange(surfaceData, 1, 15, 25);
  const heights = surfaceData.map((item) => item[2]);
  const minHeight = Math.min(...heights);
  const maxHeight = Math.max(...heights);

  const option = {
    globe: { show: false },
    title: {
      show: false, // 隐藏图表内置标题，使用外部标题
    },
    legend: {
      data: ["波峰线"],
      textStyle: {
        color: "#38e1ff",
        fontSize: 16,
        fontWeight: "bold",
      },
      right: "10%",
      top: "0",
    },
    tooltip: {
      formatter: (params) => {
        if (params.seriesType === "surface") {
          return `经度: ${params.value[0].toFixed(4)}<br>
                  纬度: ${params.value[1].toFixed(4)}<br>
                  SSH: ${params.value[2].toFixed(2)}`;
        }
        return `内波<br>经度: ${params.value[0].toFixed(
          4
        )}<br>纬度: ${params.value[1].toFixed(4)}`;
      },
    },
    visualMap: {
      seriesIndex: [0],
      min: minHeight,
      max: maxHeight,
      calculable: true,
      inRange: {
        color: [
          "#313695",
          "#4575b4",
          "#74add1",
          "#abd9e9",
          "#e0f3f8",
          "#ffffbf",
          "#fee090",
          "#fdae61",
          "#f46d43",
          "#d73027",
          "#a50026",
        ],
      },
      textStyle: {
        color: "#fff",
      },
      right: "10%",
      bottom: "20%",
    },
    xAxis3D: {
      type: "value",
      name: "经度",
      min: lonRange.min,
      max: lonRange.max,
      nameTextStyle: {
        color: "#38e1ff",
        fontSize: 12,
      },
      axisLabel: {
        color: "#ffffff",
        fontSize: 10,
      },
    },
    yAxis3D: {
      type: "value",
      name: "纬度",
      min: latRange.min,
      max: latRange.max,
      nameTextStyle: {
        color: "#38e1ff",
        fontSize: 12,
      },
      axisLabel: {
        color: "#ffffff",
        fontSize: 10,
      },
    },
    zAxis3D: {
      type: "value",
      name: "海表面高度",
      nameTextStyle: {
        color: "#38e1ff",
        fontSize: 12,
      },
      axisLabel: {
        color: "#ffffff",
        fontSize: 10,
      },
    },
    grid3D: {
      viewControl: {
        alpha: 40,
        beta: 30,
        distance: 150,
        autoRotate: false,
        autoRotateSpeed: 10,
      },
      light: {
        main: {
          intensity: 1.5,
          shadow: true,
          shadowQuality: "high",
        },
        ambient: {
          intensity: 0.7,
        },
      },
      environment: "#000",
      top: "15%",
      height: "75%",
    },
    series: [
      {
        type: "surface",
        data: surfaceData,
        wireframe: {
          show: true,
          lineStyle: {
            color: "rgba(100, 100, 100, 0.3)",
          },
        },
        itemStyle: {
          opacity: 0.8,
        },
      },
      {
        type: "line3D",
        visualMap: false,
        name: "波峰线",
        data: roadData[0].coords,
        lineStyle: {
          width: 4,
          color: "#000000",
          opacity: 1,
        },
        itemStyle: {
          color: "#000000",
          emphasis: { color: "#ff0000" },
        },
        effect: {
          show: true,
          trailWidth: 4,
          trailLength: 0.2,
          trailOpacity: 0.8,
          trailColor: "#000000",
        },
        zlevel: 2,
      },
    ],
  };

  chartInstance.setOption(option);
};

watch(
  () => [props.gridData.value, props.roadPath.value],
  () => {
    updateChart();
  },
  { deep: true }
);

onMounted(() => {
  initChart();
  if (boxWrapRef.value) {
    const rect = boxWrapRef.value.getBoundingClientRect();
    currentPos.value = { x: rect.left, y: rect.top };
  }
});

onBeforeUnmount(() => {
  if (chartInstance) {
    try {
      const dom = chartInstance.getDom();
      if (dom) {
        const canvas = dom.querySelector("canvas");
        if (canvas) {
          const gl =
            canvas.getContext("webgl") ||
            canvas.getContext("experimental-webgl");
          if (gl) {
            const loseContext = gl.getExtension("WEBGL_lose_context");
            if (loseContext) loseContext.loseContext();
          }
        }
      }
      chartInstance.dispose();
    } catch (e) {
      console.warn("释放图表资源失败:", e);
    }
    chartInstance = null;
  }
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
  document.removeEventListener("mousemove", handleResizeMove);
  document.removeEventListener("mouseup", handleResizeEnd);
});
</script>

<template>
  <div
    class="popup-container"
    :style="{
      left: `${currentPos.x}px`,
      top: `${currentPos.y}px`,
      width: `${currentSize.width}px`,
      height: `${currentSize.height}px`,
    }"
  >
    <div class="box-wrap" ref="boxWrapRef">
      <!-- 标题栏区域 -->
      <div class="header-area" ref="headerRef" @mousedown="handleMouseDown">
        <div class="title-text">{{ title || "海表面高度" }}</div>
        <div class="close" @click="closeClick">X</div>
      </div>
      <!-- 图表区域 -->
      <div ref="chartDom" class="chart-container"></div>

      <!-- 缩放控制手柄 -->
      <div
        class="resize-handle resize-e"
        data-direction="e"
        @mousedown="handleMouseDown"
      ></div>
      <div
        class="resize-handle resize-s"
        data-direction="s"
        @mousedown="handleMouseDown"
      ></div>
      <div
        class="resize-handle resize-se"
        data-direction="se"
        @mousedown="handleMouseDown"
      ></div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.popup-container {
  position: fixed;
  z-index: 9999;
  cursor: default;
  min-width: 400px;
  min-height: 300px;
}

.box-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 10px;
  border: 1px solid #38e1ff;
  background-color: rgba(30, 80, 120, 0.7);
  box-shadow: 0 0 10px 2px #29baf1;
  animation: slide 2s;
  overflow: hidden;
  user-select: none;
}

/* 标题栏样式 */
.header-area {
  position: relative;
  height: 40px;
  background: linear-gradient(
    to right,
    rgba(20, 60, 100, 0.9),
    rgba(30, 80, 120, 0.9)
  );
  border-bottom: 1px solid #38e1ff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  cursor: grab;

  &:active {
    cursor: grabbing;
  }
}

.title-text {
  color: #38e1ff;
  font-size: 16px;
  font-weight: bold;
  text-shadow: 0 0 5px rgba(56, 225, 255, 0.7);
}

.close {
  color: #fff;
  text-shadow: 2px 2px 2px #022122;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.2s;

  &:hover {
    color: #ff6b6b;
    transform: scale(1.1);
  }
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: calc(100% - 40px); /* 减去标题栏高度 */
  padding: 10px;
  box-sizing: border-box;
}

/* 缩放控制手柄样式 */
.resize-handle {
  position: absolute;
  background: transparent;
  z-index: 10;
}

.resize-e {
  cursor: e-resize;
  width: 10px;
  height: 100%;
  right: 0;
  top: 0;
}

.resize-s {
  cursor: s-resize;
  width: 100%;
  height: 10px;
  bottom: 0;
  left: 0;
}

.resize-se {
  cursor: se-resize;
  width: 15px;
  height: 15px;
  right: 0;
  bottom: 0;
  background: #38e1ff;
  opacity: 0;
  transition: opacity 0.2s;
}

.box-wrap:hover .resize-se {
  opacity: 0.8;
}

@keyframes slide {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
